<?php
/**
 * Created by PhpStorm.
 * User: 睿
 * Date: 2017-11-14
 * Time: 8:46
 */

namespace app\store\controller;


use controller\BasicAdmin;
use service\DataService;
use think\Db;

class Goodsorder extends BasicAdmin
{
    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'StoreOrderGoods';

    /**
     * 配方列表
     * @return array
     */
    public function index()
    {
        $this->title = '待订货商品配方列表';
        $get = $this->request->get();

        $store_id = session('user')['store_id'];

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_category c', 'g.cat_id=c.id', 'LEFT'],
            ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
        ];

        $db = Db::name($this->table)->alias('a')->where('a.store_id', $store_id)->where('a.is_deleted', 0)->where('a.status', 0)->where('is_diannei',0)->field('g.name,g.unit,c.title as cname,a.id,a.addtime,g.unit,a.num,s.title,a.signal_chengben,a.chengben')->join($join);
        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀

        return parent::_list($db);

    }

    /**
     * 商品配方添加
     * @return array|string
     */
    public function plus()
    {
        $store_id = session('user')['store_id'];
        if (request()->ispost()) {
            if (!input('goods_id'))
                $this->error('请选择一种商品');
            if (!input('goods_spec_id') && input('goods_id') && db('goods')->find(input('goods_id'))['is_spec'] == 1)
                $this->error('请选择一种属性');
            if(empty(input('num'))){
                $this->error('请输入订货数量','');
            }

            $goods_stock = db('goods_spec_detail')->where('id',input('goods_spec_id'))->find();

            if(input('num') > $goods_stock['stock']){
                $this->error('申请的订货数量不能超过限购数量','');
            }


            if (input('goods_spec_id')){
                $spec_id = input('goods_spec_id');
                $peifang_ids = db('goods_spec_detail')->where('id',$spec_id)->value('peifang_ids');
                if(!empty($peifang_ids)){
                    $sql = "select sum(chengben_price) as signal_chengben from ys_goods_peifang where id in (".$peifang_ids.")";
                    $signal_chengben = Db::query($sql)[0]['signal_chengben'];
                    $chengben = input('num')*$signal_chengben;
                }else{
                    $signal_chengben = 0;
                    $chengben = 0;
                }

            }else{
                $goods_spec_detail = db('goods_spec_detail')->where('goods_id',input('goods_id'))->where('specs',0)->field('id,peifang_ids')->find();
                $spec_id = $goods_spec_detail['id'];
                if(!empty($spec_id)){
                    $sql = "select sum(chengben_price) as signal_chengben from ys_goods_peifang where id in (".$goods_spec_detail['peifang_ids'].")";
                    $signal_chengben = Db::query($sql)[0]['signal_chengben'];
                    $chengben = input('num')*$signal_chengben;
                }else{
                    $signal_chengben = 0;
                    $chengben = 0;
                }

            }

            //订货配方
            $order_goods_id = db($this->table)->insertGetId(['goods_id' => input('goods_id'), 'goods_spec_id' => $spec_id, 'num' => input('num'),'signal_chengben'=>$signal_chengben,'chengben'=>$chengben, 'store_id' => $store_id, 'addtime' => time()]);

            if ($order_goods_id)
                $this->success('配方添加成功！', '');
        } else {
            $cat = db('goods_category')->where('is_exp',0)->select();
            $this->assign('cat', $cat);

            return $this->_form($this->table, 'plus');
        }
    }

    public function goods()
    {
        $goods = db('goods')->where('cat_id', input('cat_id'))->where('store_id','0')->where('is_deleted',0)->where('status',1)->select();
        return $goods;
    }

    public function spec()
    {
        $spec = db('goods_spec_detail')->where(['goods_id'=>input('goods_id'),'is_deleted'=>0])->select();
        return $spec;
    }

    /**
     * 编辑
     * @return array|string
     */
    public function edit()
    {
        if(request()->isPost()){
            $post =input('post.');

            $spec_id = db('store_order_goods')->where('id',$post['id'])->value('goods_spec_id');
            $stock = db('goods_spec_detail')->where('id',$spec_id)->value('stock');
            if($post['num'] > $stock){
                $this->error('订货数量不能超过限购数量，请重新填写','');
            }

            $peifang_ids = db('goods_spec_detail')->where('id',$spec_id)->value('peifang_ids');
            if(!empty($peifang_ids)){
                $sql = "select sum(chengben) as signal_chengben from ys_goods_peifang where id in (".$peifang_ids.")";
                $signal_chengben = Db::query($sql)[0]['signal_chengben'];
                $chengben = $post['num']*$signal_chengben;
            }else{
                $signal_chengben = 0;
                $chengben = 0;
            }

            $flag = db('store_order_goods')->where('id',$post['id'])->update(['num'=>$post['num'],'signal_chengben'=>$signal_chengben,'chengben'=>$chengben]);
            $flag!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }
        $cat = db('goods_category')->select();
        $this->assign('cat', $cat);

        return $this->_form($this->table, 'plus');
    }


    /**
     * 删除
     */
    public function del()
    {
        $id = input('id');
        $res = db('store_order_goods')->where('id',$id)->delete();
        $res>0?$this->success('删除成功',''):$this->error('删除成功','');
//        if (DataService::update($this->table)) {
//            $this->success("配方删除成功！", '');
//        }
//        $this->error("配方删除失败，请稍候再试！");
    }

    /**
     * 生成订货单
     * @throws \think\Exception
     */
    public function order()
    {
        if (DataService::update($this->table)) {
            $sn = build_order_no();
            $store_id = session('user')['store_id'];
            $i = db('store_order')->insertGetId(['sn' => $sn, 'addtime' => time(), 'store_id' => $store_id,'admin_id'=>session('user.id')]);

            $ids = input('id');
            $sql = "select sum(signal_chengben) as signal_chengben,sum(chengben) as chengben from ys_store_order_goods where id in (".$ids.")";
            $chengben_result = Db::query($sql);          //成本价
            db('store_order')->where('id',$i)->update(['chengben'=>$chengben_result[0]['chengben']]);


            $ids = explode(',', $ids);
            //遍历商品配方
            $status = 1;//循环报错为0
            foreach ($ids as $id) {
                $ret = db($this->table)->where('id', $id)->update(['order_id' => $i]);
                if ($ret === false)
                    $status = 0;
            }
            if ($status == 1)
                $this->success("订货单生成成功！", '');
        }
        $this->error("订货单生成失败，请稍候再试！");
    }

}